#!/usr/bin/env python

import os
import lib.component
import dateutil.parser

from datetime import datetime


class Post(lib.component.Namespace):
    """
    Object represent json or xml data from booru site.

    Attributes:
        - id: An integer indicating the post id in its host.
        - host: Host object.
        - search: Search object.
        - md5: A string of md5 representation.
        - height: An integer of image height.
        - width: An integer of image width.
        - size: An integer of image file size.
        - extension: A string of image type.
        - created_at: A datetime when the post created.

            Booru site didn't agree in the format. Some booru use timestamp,
            while the other use datetime.
        - url: A url where the image located.
        - tags: A set containing all tags for post.
    """

    id = None
    """
    An integer indicating the post id in its host.

    @type: int
    """

    host = None
    """
    Host object.

    @type: model.Host
    """

    search = None
    """
    Search object.

    @type: model.Search
    """

    md5 = None
    """
    An MD5 hash that uniquely identifies the image file.

    @type: str
    """

    width = None
    """
    An integer of image width.

    @type: int
    """

    height = None
    """
    An integer of image height.

    @type: int
    """

    size = None
    """
    An integer of image file size.

    @type: int
    """

    extension = None
    """
    A string explaining the image type.

    @type: str(4)
    """

    created_at = None
    """
    A datetime when the post created.

    Booru site didn't agree in the format. Some booru use timestamp, while the
    other use datetime.

    @type: int or str
    """

    url = None
    """
    A url where the image located.

    @type: str
    """

    tags = None
    """
    A set containing all tags for post.

    @type: set
    """

    def __init__(self, host, search):
        """
        Initialize Post.

        @param host: Host object.
        @type host: model.Host
        @param search: Search object.
        @type search: model.Search
        @return: None
        @rtype: None
        """

        super(Post, self).__init__()

        self.host = host
        self.search = search

    def load(self, post):
        """
        Load post data to object.

        @param post: Post data from booru site.
        @return: bool
        """

        try:
            self.id = post['id']
            self.md5 = post['md5'].lower()
            self.url = post['file_url']
            self.size = post['file_size']
        except KeyError:
            return False

        if 'width' in post:
            self.width = post['width']
        elif 'image_width' in post:
            self.width = post['image_width']
        else:
            return False

        if 'height' in post:
            self.height = post['height']
        elif 'image_height' in post:
            self.height = post['image_height']
        else:
            return False

        if 'tags' in post:
            tag = post['tags']
        elif 'tag_string' in post:
            tag = post['tag_string']
        else:
            return False

        tags = [x.strip() for x in tag.strip().split(' ')]
        self.tags = set(tags) - {''}

        filename = post['file_url'].split('/')[-1]
        self.extension = os.path.splitext(filename)[1][1:].lower()

        created_at = post['created_at']
        if isinstance(created_at, (int, long)):
            self.created_at = datetime.fromtimestamp(float(created_at))
        else:
            self.created_at = dateutil.parser.parse(post['created_at'])

        return True
